package org.oos.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * This class is used to format Dates
 * 
 * @author pablo.gonzalez@11870.com
 * 
 */
public class AtomDate extends Date {

	private static final long serialVersionUID = -6134610220767481577L;

	public AtomDate(String rawDate) {
		super();
		if (!format(rawDate, this)) {
			throw new IllegalArgumentException("Incorrect AtomDate Format");
		}
	}

	private static DateFormat format = new SimpleDateFormat(
			"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

	/**
	 * This array is taken from
	 * http://www.koders.com/java/fidDBC85D14D02AA458CE8B8A25256E176EAC6EA748
	 * .aspx?s=cdef:parser#L38
	 */
	// private static final String[] W3CDATETIME_MASKS = {
	// "yyyy-MM-dd'T'HH:mm:ss.SSSz", "yyyy-MM-dd't'HH:mm:ss.SSSz",
	// "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "yyyy-MM-dd't'HH:mm:ss.SSS'z'",
	// "yyyy-MM-dd'T'HH:mm:ssz", "yyyy-MM-dd't'HH:mm:ssz",
	// "yyyy-MM-dd'T'HH:mm:ss'Z'", "yyyy-MM-dd't'HH:mm:ss'z'",
	// "yyyy-MM-dd'T'HH:mmz", "yyyy-MM'T'HH:mmz", "yyyy'T'HH:mmz",
	// "yyyy-MM-dd't'HH:mmz", "yyyy-MM-dd'T'HH:mm'Z'",
	// "yyyy-MM-dd't'HH:mm'z'", "yyyy-MM-dd", "yyyy-MM", "yyyy" };

	/**
	 * Recursively checks if the format provided is correct. Once it finds a
	 * format it will remain with that format until another format is required.
	 * 
	 * @param rawDate
	 * @return
	 */
	private final boolean format(String rawDate, Date date) {
		if (format != null) {
			try {
				date.setTime(format.parse(rawDate).getTime());
				return true;
			} catch (ParseException e) {
				// ignore exception
			}
		} else {

			// for (String mask : W3CDATETIME_MASKS) {
			// format = new SimpleDateFormat(mask);
			// if (format(rawDate, date))
			// return true;
			// }
		}
		return false;
	}
	
	public static String toString(Date date) {
		return format.format(date);
	}

}
